import {createRouter} from "../router";

const whiteList = ["/login"]; //不需要重定向的白名单
export default function ({store, app, redirect, $axios, route}) {
    const token = app.$cookies.get("token");
    const router = createRouter();
    router.beforeEach(async (to, from, next) => {
        const storeToken = store.state.authentication.token;
        if (token || storeToken) {
            const hasRoles = store.getters["permission/getRoutes"];
            // const d = "-------- 全部菜单 --------";
            // console.log(`%c ${d}`, "color:blue;font-size:25px");
            // console.log(hasRoles)
            // console.log(`%c ${d}`, "color:blue;font-size:25px");
            const status = hasRoles.length === 0;
            if (status) {
                try {
                    //获取用户路由
                    const {routes} = await store.dispatch("authentication/GETUSERINFO");
                    //获取用户首页权限
                    await store.dispatch("PermisionsStorage/setHasPermision");
                    //获取路由鉴权
                    const accessRoutes = await store.dispatch(
                        "permission/generateRoutes",
                        routes
                    );
                    router.addRoutes(accessRoutes);
                    next({...to, replace: true});
                } catch (error) {
                    next('/login');
                }
            } else {
                next();
            }
        } else {
            if (whiteList.indexOf(to.path) !== -1) {
                next();
            } else {
                next("/login");
            }
        }
    });
}
